﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Citi.HeadCount.Domain.Repository;
using Citi.HeadCount.WebUI.Models;
using Citi.HeadCount.Domain;
using System.Threading.Tasks;

namespace Citi.HeadCount.WebUI.Controllers
{
    public class RuleController : Controller
    {
        public ActionResult Index(int ruleResultId)
        {
            var models = GetRulesModelByResultId(ruleResultId);
            return PartialView(models);
        }

        private static IEnumerable<RuleViewModel> GetRulesModelByResultId(int ruleResultId)
        {
            var rules = new RuleRepository().GetRulesByResultId(ruleResultId);
            return RuleViewModel.CreateModel(rules);
        }

        public ActionResult Create(int ruleResultId = 0)
        {
            FillViewBag();
            return PartialView(new RuleViewModel { RuleResultId = ruleResultId });
        }

        private void FillViewBag()
        {
            ViewBag.RuleTypes = new RuleType().ToSelectList(true, true, "-");
        }

        [HttpPost]
        public ActionResult Create(RuleViewModel model)
        {
            try
            {
                if (model.RuleResultId == 0)
                {
                    var ruleResult = new RuleResult { LastUpdate = DateTime.Today, ReferenceDate = DateTime.Today, Active = true, Exception = false };
                    new RepositoryBase<RuleResult>().Save(ruleResult);
                    model.RuleResultId = ruleResult.Id;
                }

                var rule = new Rule { LastUpdate = DateTime.Today, ReferenceDate = DateTime.Today, Level = model.Level, RuleResultId = model.RuleResultId, Type = (RuleType)model.Type, Value = model.Value };
                new RepositoryBase<Rule>().Save(rule);

                var models = GetRulesModelByResultId(model.RuleResultId);

                return PartialView("Index", models);
            }
            catch
            {
                return null;
            }
        }
    }
}
